# -*- coding: utf-8 -*-
# vim:set noet ts=4:
#
# scim-python
#
# Copyright (c) 2007-2008 Huang Peng <shawn.p.huang@gmail.com>
#
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330,
# Boston, MA  02111-1307  USA
#
# $Id: $
#
import scim
import gtk 
import os
import sys
import gtk.glade
import gobject
import commands
try:
	from PYDict import *
except:
	pathname = os.path.dirname (__file__)
	path = os.path.abspath(pathname)
	print path
	path = os.path.join (path, "../engine/PinYin")
	path = os.path.abspath(path)
	print path
	sys.path.append(path)
	from PYDict import *

from gettext import dgettext
_ = lambda a : dgettext ("scim-python", a)
N_ = lambda x : x

gtk.glade.textdomain("scim-python")

shuangpin_schema_list = SHUANGPIN_SCHEMAS.keys()
pinyin_schema_list = [N_("QuanPin"),N_("JianPin"),N_("ShuangPin")]
ConfigBase = "/IMEngine/Python/ZhengJu/"
Pass = lambda get: get
Config = {
"ShuangPinSchema" : ( lambda get: shuangpin_schema_list.index(get) ,
				lambda set: shuangpin_schema_list[set],
				"MSPY"),
"PinYinSchema" : ( lambda get: pinyin_schema_list.index(get) ,
				lambda set: pinyin_schema_list[set],
				"JianPin"),
"LargeCharset" :( Pass,Pass,False),
"CreateUserWords" :( Pass,Pass,True),
"CreateUserPhrases" :( Pass,Pass,True),
"AdjustWordFreq" :( Pass,Pass,True),
"ProgressivePrompt" : ( Pass,Pass,True)
}

class ZhengJuSetupUI (gtk.VBox):

	def __init__ (self):
		gtk.VBox.__init__ (self)
		self._values = {}
		self.orgin_value = {}
		self._create_ui ()
		self.show_all ()
		
	def _create_ui (self):
		pathname = os.path.dirname (__file__)
		path = os.path.abspath(pathname)
		self.xml = gtk.glade.XML(path+'/ZhengJuUI.glade',root="top")
		self.pack_start (self.xml.get_widget("top"))
		
		gtk_pinin_schema = self.xml.get_widget("PinYinSchema")
		liststore = gtk.ListStore(str)
		for k in pinyin_schema_list:
			liststore.append([_(k)])
		gtk_pinin_schema.set_model(liststore)
		
		gtk_shuangpin_schema = self.xml.get_widget("ShuangPinSchema")
		liststore = gtk.ListStore(str)
		for k in shuangpin_schema_list:
			liststore.append([_(k)])
		gtk_shuangpin_schema.set_model(liststore)

		train_button = self.xml.get_widget("Train")
		train_button.connect('clicked', self.train_callback)
		
	def get_name (self):
		return _("ZhengJu")
	
	def train_callback(self,button):
		dialog = gtk.FileChooserDialog(_("Choose A Plain Text File"),buttons=
			(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_ACCEPT))
		if dialog.run() == gtk.RESPONSE_ACCEPT:
			files = dialog.get_filenames()
		else:
			files = []
		dialog.destroy()
		for i in files:
			pathname = os.path.dirname (__file__)
			path = os.path.abspath(pathname)
			path = os.path.join (path, "../../engine/PinYin/ZhengJu.py -f ")
			result = commands.getstatusoutput("python " +path + i)
			if result[0]==0:
				message = gtk.MessageDialog(buttons=gtk.BUTTONS_OK,
					message_format = _("Train Successful"))
			else:
				message = gtk.MessageDialog(buttons=gtk.BUTTONS_OK,
					message_format = _("Train Failed"))
				message.format_secondary_text(result[1])
			message.run()
			message.destroy()

	
	def load_config(self,config):
		for k, v in Config.items():
			value = config.read (ConfigBase+k, v[2])
			self.xml.get_widget(k).set_active(v[0](value))
			self.orgin_value[k] = value
	
	def save_config (self, config):
		for k, v in Config.items():
			value = v[1](self.xml.get_widget(k).get_active())
			config.write (ConfigBase+k, value)
	
	def query_changed (self):
		for k, v in Config.items():
			if v[1](self.xml.get_widget(k).get_active()) != self.orgin_value[k]:
				return True
		return False

window = None

def mod_create_ui ():
	global window
	if window != None:
		return window
	try:
		window = ZhengJuSetupUI()
		window.show_all ()
		return window
	except:
		import traceback
		traceback.print_exc ()
		return None

def mod_load_config (config):
	try:
		window.load_config (config)
	except:
		import traceback
		traceback.print_exc ()

def mod_save_config (config):
	try:
		window.save_config (config)
	except:
		import traceback
		traceback.print_exc ()

def mod_query_changed ():
	try:
		if window.query_changed ():
			return True
	except:
		import traceback
		traceback.print_exc ()
		return False

if __name__ == "__main__":
	w = gtk.Window()
	w.set_title(_("ZhengJu"))
	w.add(ZhengJuSetupUI())
	w.show()
	gtk.main()
